package com.ruoyi.ldzlsb.controller;

import java.util.List;
import java.util.Date;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.ldzlsb.domain.SbMaintenanceRecord;
import com.ruoyi.ldzlsb.service.ISbMaintenanceRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 保养单Controller
 * 
 * @author anli
 * @date 2025-01-11
 */
@RestController
@RequestMapping("/sb/maintenance/record")
public class SbMaintenanceRecordController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(SbMaintenanceRecordController.class);
    
    @Autowired
    private ISbMaintenanceRecordService sbMaintenanceRecordService;
    
    /**
     * 注册自定义日期编辑器，处理多种日期格式
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // 添加多种日期格式支持
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
        
        // 设置为宽松模式
        dateFormat1.setLenient(true);
        dateFormat2.setLenient(true);
        
        // 创建支持多种日期格式的自定义编辑器
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat1, true) {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                if (text == null || text.trim().isEmpty()) {
                    setValue(null);
                    return;
                }
                
                try {
                    // 尝试使用第一种格式
                    setValue(dateFormat1.parse(text));
                } catch (Exception e1) {
                    try {
                        // 尝试使用第二种格式
                        setValue(dateFormat2.parse(text));
                    } catch (Exception e2) {
                        try {
                            // 尝试其他可能的格式
                            if (text.matches("\\d{4}-\\d{1,2}")) {
                                // 处理 yyyy-MM 格式
                                setValue(new SimpleDateFormat("yyyy-MM").parse(text));
                            } else if (text.matches("\\d{4}/\\d{1,2}/\\d{1,2}")) {
                                // 处理 yyyy/MM/dd 格式
                                setValue(new SimpleDateFormat("yyyy/MM/dd").parse(text));
                            } else if (text.matches("\\d{4}/\\d{1,2}/\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}")) {
                                // 处理 yyyy/MM/dd HH:mm:ss 格式
                                setValue(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(text));
                            } else if (text.matches("\\d{8}")) {
                                // 处理 yyyyMMdd 格式
                                setValue(new SimpleDateFormat("yyyyMMdd").parse(text));
                            } else if (text.matches("\\d{14}")) {
                                // 处理 yyyyMMddHHmmss 格式
                                setValue(new SimpleDateFormat("yyyyMMddHHmmss").parse(text));
                            } else {
                                throw new IllegalArgumentException("无法解析日期: " + text);
                            }
                        } catch (Exception e3) {
                            throw new IllegalArgumentException("无法解析日期: " + text);
                        }
                    }
                }
            }
        });
    }

    /**
     * 查询保养单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SbMaintenanceRecord sbMaintenanceRecord)
    {
        startPage();
        List<SbMaintenanceRecord> list = sbMaintenanceRecordService.selectSbMaintenanceRecordList(sbMaintenanceRecord);
        return getDataTable(list);
    }

    /**
     * 查询保养单列表（包含关联信息）
     */
    @GetMapping("/listWithInfo")
    public TableDataInfo listWithInfo(SbMaintenanceRecord sbMaintenanceRecord)
    {
        startPage();
        List<SbMaintenanceRecord> list = sbMaintenanceRecordService.selectSbMaintenanceRecordWithInfoList(sbMaintenanceRecord);
        return getDataTable(list);
    }

    /**
     * 导出保养单列表
     */
    @Log(title = "保养单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SbMaintenanceRecord sbMaintenanceRecord)
    {
        List<SbMaintenanceRecord> list = sbMaintenanceRecordService.selectSbMaintenanceRecordList(sbMaintenanceRecord);
        ExcelUtil<SbMaintenanceRecord> util = new ExcelUtil<SbMaintenanceRecord>(SbMaintenanceRecord.class);
        util.exportExcel(response, list, "保养单数据");
    }

    /**
     * 获取保养单详细信息
     */
    @GetMapping(value = "/{recordId}")
    public AjaxResult getInfo(@PathVariable("recordId") Long recordId)
    {
        return success(sbMaintenanceRecordService.selectSbMaintenanceRecordByRecordId(recordId));
    }

    /**
     * 新增保养单
     */
    @Log(title = "保养单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SbMaintenanceRecord sbMaintenanceRecord)
    {
        return toAjax(sbMaintenanceRecordService.insertSbMaintenanceRecord(sbMaintenanceRecord));
    }

    /**
     * 修改保养单
     */
    @Log(title = "保养单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SbMaintenanceRecord sbMaintenanceRecord)
    {
        return toAjax(sbMaintenanceRecordService.updateSbMaintenanceRecord(sbMaintenanceRecord));
    }

    /**
     * 删除保养单
     */
    @Log(title = "保养单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{recordIds}")
    public AjaxResult remove(@PathVariable Long[] recordIds)
    {
        return toAjax(sbMaintenanceRecordService.deleteSbMaintenanceRecordByRecordIds(recordIds));
    }

    /**
     * 根据保养单编号获取保养单信息
     */
    @GetMapping("/code/{recordCode}")
    public AjaxResult getInfoByCode(@PathVariable("recordCode") String recordCode)
    {
        return success(sbMaintenanceRecordService.selectSbMaintenanceRecordByRecordCode(recordCode));
    }

    /**
     * 根据保养计划ID获取保养单列表
     */
    @GetMapping("/plan/{planId}")
    public AjaxResult listByPlanId(@PathVariable("planId") Long planId)
    {
        List<SbMaintenanceRecord> list = sbMaintenanceRecordService.selectSbMaintenanceRecordByPlanId(planId);
        return success(list);
    }

    /**
     * 根据设备ID获取保养单列表
     */
    @GetMapping("/equipment/{equipmentId}")
    public AjaxResult listByEquipmentId(@PathVariable("equipmentId") Long equipmentId)
    {
        List<SbMaintenanceRecord> list = sbMaintenanceRecordService.selectSbMaintenanceRecordByEquipmentId(equipmentId);
        return success(list);
    }

    /**
     * 根据保养人员ID获取保养单列表
     */
    @GetMapping("/maintainer/{maintainerId}")
    public AjaxResult listByMaintainerId(@PathVariable("maintainerId") Long maintainerId)
    {
        List<SbMaintenanceRecord> list = sbMaintenanceRecordService.selectSbMaintenanceRecordByMaintainerId(maintainerId);
        return success(list);
    }

    /**
     * 更新保养单状态
     */
    @Log(title = "更新保养单状态", businessType = BusinessType.UPDATE)
    @PutMapping("/status/{recordId}/{status}")
    public AjaxResult updateStatus(@PathVariable("recordId") Long recordId, @PathVariable("status") String status)
    {
        SbMaintenanceRecord record = new SbMaintenanceRecord();
        record.setRecordId(recordId);
        record.setMaintenanceStatus(status);
        return toAjax(sbMaintenanceRecordService.updateSbMaintenanceRecord(record));
    }

    /**
     * 开始执行保养
     */
    @Log(title = "开始执行保养", businessType = BusinessType.UPDATE)
    @PostMapping("/start-maintenance/{recordId}")
    public AjaxResult startMaintenance(@PathVariable("recordId") Long recordId)
    {
        // 获取保养单详情
        SbMaintenanceRecord record = sbMaintenanceRecordService.selectSbMaintenanceRecordByRecordId(recordId);
        if (record == null) {
            return AjaxResult.error("保养单不存在");
        }
        
        // 只对待保养状态的保养单更新状态为保养中
        if ("0".equals(record.getMaintenanceStatus())) {
            // 更新保养单状态为"保养中"
            record = new SbMaintenanceRecord();
            record.setRecordId(recordId);
            record.setMaintenanceStatus("1"); // 保养中
            record.setStartTime(new Date());
            sbMaintenanceRecordService.updateSbMaintenanceRecord(record);
            
            return AjaxResult.success("开始执行保养");
        } else if ("1".equals(record.getMaintenanceStatus())) {
            // 如果已经是保养中状态，则不做状态变更
            return AjaxResult.success("继续执行保养");
        } else if ("2".equals(record.getMaintenanceStatus())) {
            // 如果已完成，提示用户但仍然允许查看
            return AjaxResult.success("该保养单已完成，可以查看详情");
        } else {
            // 其他状态（如已取消等）不允许执行
            return AjaxResult.error("该保养单当前状态不允许执行");
        }
    }
} 